using System;
using System.Collections;
using System.Web.UI.WebControls;
using PHSRAG.Insight21.Common.Pages;
using PHSRAG.Insight21.Policy;
using PHSRAG.Insight21.Purchasing;
using PHSRAG.Utility;
using Helper=PHSRAG.WebControls.Helper;
using PurchasingTransaction = PHSRAG.Insight21.Purchasing;

namespace PHSRAG.Insight21
{
    /// <summary>
    /// The DeleteUserOrder class supports the DeleteUserOrder.aspx popup
    /// It helps the user in deleting a set of user orders.
    /// The page redirects the user to the UserOrderSummary page after the delete operation is completed.
    /// </summary>
    public partial class DeleteUserOrder : NoCachePage
    {
        #region Constants

        private const string ClosePopupJSKey = "ClosePopup_DC475213-3E90-4558-BBAE-D3B2D14C8675";
        private const string OrderAmountLabelName = "orderAmount";
        private const string OrderIDsListKey = "OrderIDsList_DC475213-3E90-4558-BBAE-D3B2D14C8675";
        private const string OrderNumberLabelName = "orderNumber";
        private const string OrderTypeLabelName = "orderType";
        private const string SetFocusKey = "SetFocus_DC475213-3E90-4558-BBAE-D3B2D14C8675";
        private const string UserOrderSummaryFormName = "UserOrderSummary";

        #endregion

        #region Instance variables (Private)

        private ICachePolicy cachePolicy;
        private ICachePolicy pageCachePolicy;
        private ViewStateCachePolicy viewStateCachePolicy;

        #endregion

        #region Properties

        /// <summary>
        ///	Increments user order version number used to determine whether user orders have been added/edited/deleted 
        ///	so that pages, such as Budget overview, that report on them can reload themselves.
        /// </summary>
        private int UserOrdersVersion
        {
            get
            {
                object version = pageCachePolicy.GetCachedObject(Keys.UserOrdersVersionKey);
                return version == null ? 0 : (int) version;
            }
            set { pageCachePolicy.Cache(Keys.UserOrdersVersionKey, value); }
        }

        #endregion

        #region Event Handlers

        /// <summary>
        /// Handler for the event raised when the page is being loaded.
        /// Retrieve the list of order ids from the pageCachePolicy and save it in viewState
        /// Databind all the controls on the page
        /// </summary>
        /// <param name="sender">Control which raised the event</param>
        /// <param name="e">Argument associated with the event</param>
        protected void OnPageLoad(object sender, EventArgs e)
        {
            ClientScript.RegisterStartupScript
                (GetType(), SetFocusKey
                    , "<script>document.focus();</script>");

            annunciator.Message = string.Empty;
            annunciator.Title = string.Empty;

            if (!IsPostBack)
            {
                Hashtable dictionary = pageCachePolicy.GetCachedObject(Keys.IncomingDataKey) as Hashtable;

                string orderIDList = string.Empty;

                if (dictionary != null && dictionary.ContainsKey(Keys.UserOrderIDListKey))
                {
                    orderIDList = (dictionary[Keys.UserOrderIDListKey] == null)
                        ? string.Empty : dictionary[Keys.UserOrderIDListKey].ToString();
                }

                try
                {
                    if (!orderIDList.Equals(string.Empty))
                    {
                        prompt.Text = "Are you sure you want to delete the following user order(s)?";

                        string[] idsArray = orderIDList.Split(new char[] {','});

                        ArrayList userOrdersList = new ArrayList();

                        foreach (string orderID in idsArray)
                        {
                            if (!orderID.Equals(string.Empty))
                            {
                                userOrdersList.Add
                                    (UserOrderUtility.LoadUserOrder(Convert.ToInt32(orderID), cachePolicy));
                            }
                        }

                        userOrders.DataSource = userOrdersList;
                        userOrders.DataBind();

                        viewStateCachePolicy.Cache(OrderIDsListKey, orderIDList);
                    }

                    else
                    {
                        prompt.Text = "No orders were selected for deletion";
                        deleteUserOrders.Visible = false;
                    }
                    pageCachePolicy.UnCache(Keys.IncomingDataKey);
                }
                catch (Exception ex)
                {
                    annunciator.Message = ExceptionReport.GetExceptionInfo(ex, false);
                }
                cancelDelete.Attributes.Add("onclick", "javascript:window.close();");
            }
        }

        /// <summary>
        /// Handler for the event raised when a row in the repeater is databound.
        /// Bind the labels inside the Repeater with the data from the user order object 
        /// </summary>
        /// <param name="sender">Control which raised the event</param>
        /// <param name="e">Argument associated with the event</param>
        private void OnItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            RepeaterItem userOrderItem = e.Item;

            if (userOrderItem.ItemType == ListItemType.AlternatingItem || userOrderItem.ItemType == ListItemType.Item)
            {
                UserOrder userOrder = (UserOrder) userOrderItem.DataItem;

                ((Label) userOrderItem.FindControl(OrderTypeLabelName)).Text =
                    Enum.Parse(typeof (UserOrderUtility.UserOrderType)
                        , userOrder.OrderTypeID.ToString(), false).ToString();
                ((Label) userOrderItem.FindControl(OrderNumberLabelName)).Text = userOrder.OrderNumber;
                ((Label) userOrderItem.FindControl(OrderAmountLabelName)).Text = Convert.ToDecimal(userOrder.TotalAmount).ToString("c", Helper.ZeroDecimals());
            }
        }

        /// <summary>
        /// Handler for the event raised when the delete button is clicked on the screen
        /// Remove the UserOrderSummary instance from the cache to enable the UserOderSummary page to reload the data
        /// </summary>
        /// <param name="sender">Control which raised the event</param>
        /// <param name="e">Argument associated with the event</param>
        protected void OnDelete(object sender, EventArgs e)
        {
            try
            {
                UserOrderUtility.DeleteUserOrders(
                    viewStateCachePolicy.GetCachedObject(OrderIDsListKey).ToString()
                    , cachePolicy);

                // increment user order version to show that there has been a change
                ++UserOrdersVersion;

                ClientScript.RegisterStartupScript
                    (GetType(), ClosePopupJSKey
                        , "<script >self.opener.window.document.forms(0).submit(); self.close();  </script>"
                    );
            }
            catch (Exception ex)
            {
                annunciator.Message = ExceptionReport.GetExceptionInfo(ex, false);
            }
        }

        #endregion

        #region Web Form Designer generated code

        protected override void OnInit(EventArgs e)
        {
            InitializeComponent();
            base.OnInit(e);

            cachePolicy = (Policy.ICachePolicy) Session[Policy.Names.CachePolicyKey];
            viewStateCachePolicy = new PHSRAG.Insight21.Policy.ViewStateCachePolicy(this.ViewState);
            pageCachePolicy = (Policy.ICachePolicy) Session[Policy.Names.PageCachePolicyKey];
        }

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.userOrders.ItemDataBound += new System.Web.UI.WebControls.RepeaterItemEventHandler(this.OnItemDataBound);
            this.Load += new System.EventHandler(this.OnPageLoad);
        }

        #endregion
    }
}